<?php
// http://feeds.feedburner.com/WikinewsLatestNews
// http://identi.ca/api/statuses/update.json
// http://magpierss.sourceforge.net/

require_once('sub.inc.php');
define('MAGPIE_CACHE_ON', 0);			//Turn off Magpie Cache - Important
require('magpierss-0.72/rss_fetch.inc');	// Don't move this to sub

$GLOBALS['twiturl'] =  "http://twitter.com/statuses/update.json";
$GLOBALS['denturl'] = "http://identi.ca/api/statuses/update.json";


//Stage 1 -- db.rss for tasks
logEntry('DAEMON','','Daemon run starting -- Stage 1');
$res = mysqli_query($GLOBALS['con'], "SELECT * FROM `rss` WHERE `lastcheck`<=DATE_SUB(NOW(), INTERVAL `checkdelay` MINUTE)");
while($row = mysqli_fetch_array($res) ){
	logEntry('DAEMON-RSS',$row['id'],'Found RSS Feed - Scanning');
	$rss = fetch_rss($row['rssurl']);

	foreach (array_reverse($rss->items) as $item ) {
		if(preg_match("/(.*):(.*)/",$row['rsstitle'],$ray)){
			$title = $item[$ray[1]][$ray[2]];
		}else{
			$title = $item[$row['rsstitle']];			
		}
		if(preg_match("/(.*):(.*)/",$row['rsslink'],$ray)){
			$url = $item[$ray[1]][$ray[2]];
		}else{
			$url = $item[$row['rsslink']];
		}


        	if(preg_match("/(.*)\?curid=(.*)/", $url, $match)){		// Removing Curid if it exists
			$url = $match[1];
		}

		$url = clean(trim($url));
		$title = clean(trim($title));
		

		$res = mysqli_query($GLOBALS['con'], "SELECT * FROM `daemon` WHERE `hash`=sha1('$title')");		// See if this is already in the DB
		if(!mysqli_fetch_array($res)){
			$crz = createURL($url, 3, $row['domain']);
			$lastres = mysqli_query($GLOBALS['con'], "SELECT * FROM `domains` WHERE `id`='{$row['domain']}'");
			$lastrow = mysqli_fetch_array($lastres);
			if(strlen($title) >= 105){ $msg = substr($title, 0, 105) . "..."; }else{$msg = $title;}
			$msg = "$msg http://{$lastrow['tld']}/$crz #{$row['hashtag']}";
			mysqli_query($GLOBALS['con'], "INSERT INTO `daemon` (`rssid`, `message`, `hash`, `url`) VALUES ({$row['id']}, '$msg', sha1('$title'), '$url')");
			logEntry('DAEMON-NEW',mysqli_insert_id($GLOBALS['con']),"Found new RSS item & added to database: \"$title\"");
		}
	}
}


//Stage 2 -- db.daemon for entries that need tweeting
logEntry('DAEMON','','Daemon run starting -- Stage 2');
$tc = 0;$dc = 0;
$res = mysqli_query($GLOBALS['con'], "SELECT d.id,d.rssid,d.message,d.tweetid,d.dentid,r.twitun,r.twitpwd,r.dentun,r.dentpwd FROM `daemon` as d INNER JOIN `rss` as r ON d.rssid=r.id  WHERE `tweetid` IS NULL OR `dentid` IS NULL");
while($row = mysqli_fetch_array($res) ){

	if($row['twitun'] != "" && $row['twitpwd'] != ""){		// Put together Twitter Auth
		$twitauth = $row['twitun'] . ":" . $row['twitpwd'];
	}else{ $twitauth = null; }

	if($row['dentun'] != "" && $row['dentpwd'] != ""){		// Put together Dent Auth
		$dentauth = $row['dentun'] . ":" . $row['dentpwd'];
	}else{ $dentauth = null; }

	if($row['tweetid'] == "" && !is_null($twitauth)){		// Is Tweet missing & Auth good?
		$rez = post('tweet', $row['message'], $twitauth);
		$out = json_decode($rez, true);
		if($out['id']){
			mysqli_query($GLOBALS['con'], "UPDATE `daemon` SET `tweetid`='{$out['id']}' WHERE `id`='{$row['id']}'");
			logEntry('DAEMON-TWEET',$row['id'],"Successfully posted update #{$out['id']} to Twitter",$rez);
			$tc++;
		}else{
			logEntry('DAEMON-TWEET',$row['id'],"Twitter update FAILED",$rez);
		}
	}

	if($row['dentid'] == "" && !is_null($dentauth)){		// Is Dent missing & Auth good?
		$rez = post('dent', $row['message'], $dentauth);
		$out = json_decode($rez, true);
		if($out['id']){
			 mysqli_query($GLOBALS['con'], "UPDATE `daemon` SET `dentid`='{$out['id']}'  WHERE `id`='{$row['id']}'");
			logEntry('DAEMON-DENT',$row['id'],"Successfully posted update #{$out['id']} to Identica",$rez);
			$dc++;
		}else{
			logEntry('DAEMON-DENT',$row['id'],"Identica updated FAILED",$rez);
		}
	}
	
	if($tc >= 3 || $dc >= 3){
		outEarly();
	}
}

// Stage 3 - Done

logEntry('DAEMON','','Daemon run completed.');

function outEarly(){
	logEntry('DAEMON','','Daemon run terminated early due to max posts');
	exit;
}

function post($srv, $msg, $auth){
	$post = "status=".urlencode(utf8_encode($msg));
	if($srv == "tweet"){ $url = $GLOBALS['twiturl']; }
	if($srv == "dent"){ $url = $GLOBALS['denturl']; }

	$back = curlIt($url, $auth, $post);
	$back = preg_replace( '/id":(\d+)/', 'id":"\1"', $back );		// Fixes JSON_DECODE issue with > 32bit int
	//print $back;
	//print_r(json_decode($back));
	return $back;
}

function curlIt($url, $unpwd="", $post=""){
        $UA = "Mozilla/5.0 (compatible; WikinewsBot)";
        $ch = curl_init($url);
        //curl_setopt($ch, CURLOPT_VERBOSE, 1); //--Debug only
        if($unpwd != ""){
                curl_setopt($ch, CURLOPT_USERPWD, $unpwd);
        }
        if($post != ""){
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_USERAGENT, $UA);
        ob_start();
        curl_exec($ch);
        $retHTML = ob_get_contents();
        ob_end_clean();

	logEntry('CURL','',$url,curl_errno($ch) . "|" . curl_error($ch) . "|" . json_encode(curl_getinfo($ch)) . "|" . $retHTML);

//	if(curl_errno($ch)){
//		print "curl error";
//		return(curl_errno($ch) . "|" . curl_error($ch) . "|" . json_encode(curl_getinfo($ch)) . "|" . $retHTML);
//	}else{
	        return($retHTML);
//	}
        curl_close($ch);
}






